import { useState, useCallback } from 'react';
import { useAuth } from './use-auth';
import { ApiResponse } from '@/types';

interface UseApiOptions<T> {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  onSuccess?: (data: T) => void;
  onError?: (error: Error) => void;
}

export function useApi<T>({
  url,
  method = 'GET',
  onSuccess,
  onError,
}: UseApiOptions<T>) {
  const [data, setData] = useState<T | null>(null);
  const [error, setError] = useState<Error | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const { token } = useAuth();

  const execute = useCallback(async (body?: any) => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        ...(body ? { body: JSON.stringify(body) } : {}),
      });

      const responseData: ApiResponse<T> = await response.json();

      if (!response.ok) {
        throw new Error(responseData.message || '请求失败');
      }

      setData(responseData.data);
      onSuccess?.(responseData.data);
      return responseData.data;
    } catch (err) {
      const error = err as Error;
      setError(error);
      onError?.(error);
      throw error;
    } finally {
      setIsLoading(false);
    }
  }, [url, method, token, onSuccess, onError]);

  return {
    data,
    error,
    isLoading,
    execute,
  };
} 